var config = require('./config.js'); 

var constants = require('./constants.js');

var storage = require('./storage.js'); 

const equipment = require('./equipment.js');

//当前平台
let provider = "toutiao";

let code = null;

function request(params, isGetTonken) { 
	
	equipment.closePc(this);
	
	var isToken = false;
	var isAuth = true;
	if (params.url.indexOf("/p/") == 0 || params.url.indexOf("/u/") == 0) {
		isToken = true;
		if(!storage.get(constants.TOKEN_DATE)){
			uni.removeStorageSync(constants.GUO_USER_KEY);
			uni.removeStorageSync(constants.USER_TOKEN_KEY);
			uni.removeStorageSync(constants.GUO_IS_LOGIN);
			uni.removeStorageSync(constants.BIND_USER);
			uni.removeStorageSync(constants.APP_USER_INFO);
			storage.remove(constants.TOKEN_DATE);
			isAuth = false;
			uni.showToast({
				title:'登录信息已过期',
				icon:'none',
				success(res) {
					setTimeout(function(){
						uni.reLaunch({
							url:'/pages/login/login'
						})
					},1000);
				}
			})
		}
	}
	//没有认证
	if(!isAuth){
		return;
	}
    uni.request({
        url:  params.baseUrl ? config.baseUrl + params.url : config.domain + params.url,
        //接口请求地址
        data: params.data,
        header: {
			//systemType: params.miniApp != '' ? params.miniApp : undefined,
			systemType: constants.MINI_TYPE,
            'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded;charset=utf-8' : 'application/json;charset=utf-8',
            Authorization:  isToken ? uni.getStorageSync(constants.USER_TOKEN_KEY) : null,
			//Authorization:  uni.getStorageSync(constants.USER_TOKEN_KEY)
        },
        method: params.method == undefined ? 'POST' : params.method,
        dataType: 'json',
        responseType: params.responseType == undefined ? 'text' : params.responseType,
        success: function (res) {
            if (res.statusCode == 200) {
				if(res.data.code == 401){
					uni.removeStorageSync(constants.GUO_USER_KEY);
					uni.removeStorageSync(constants.USER_TOKEN_KEY);
					uni.removeStorageSync(constants.GUO_IS_LOGIN);
					uni.removeStorageSync(constants.BIND_USER);
					uni.removeStorageSync(constants.APP_USER_INFO);
					storage.remove(constants.TOKEN_DATE);
					uni.showToast({
						title:'登录信息已过期',
						icon:'none',
						success(res) {
							setTimeout(function(){
								uni.reLaunch({
									url:'/pages/login/login'
								})
								console.log(4);
								return;
							},1000);
						}
					})
				}else{
					//如果有定义了params.callBack，则调用 params.callBack(res.data)
					if (params.callBack) {
					    params.callBack(res.data);
					}
				}
                
            } else {
                if (res.statusCode == 500) {
                    uni.showToast({
                        title: '服务器异常',
                        icon: 'none'
                    });
                } else {
                    if (res.statusCode == 401) {
						uni.removeStorageSync(constants.GUO_USER_KEY);
						uni.removeStorageSync(constants.USER_TOKEN_KEY);
						uni.removeStorageSync(constants.GUO_IS_LOGIN);
						uni.removeStorageSync(constants.BIND_USER);
						uni.removeStorageSync(constants.APP_USER_INFO);
						storage.remove(constants.TOKEN_DATE);
						uni.showToast({
							title:'登录信息已过期',
							icon:'none',
							success(res) {
								setTimeout(function(){
									uni.reLaunch({
										url:'/pages/login/login'
									})
									console.log(5);
									return;
								},1000);
							}
						})
						if (params.errCallBack) {
						    params.errCallBack(res);
						}
                    } else {
                        if (res.statusCode == 400) {
                            uni.showToast({
                                title: res.data,
                                icon: 'none'
                            });
                        } else {
                            //如果有定义了params.errCallBack，则调用 params.errCallBack(res.data)
                            if (params.errCallBack) {
                                params.errCallBack(res);
                            }
                        }
                    }
                }
            }
        },
        fail: function (err) {
            uni.showToast({
                title: '服务器出了点小差',
                icon: 'none'
            });
            
        }
    });
}

function customRequest(params) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: params.url,
            method: params.method || 'GET',
            data: params.data || {},
            header: {
                //'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
                Authorization: params.login ? undefined : uni.getStorageSync(constants.USER_TOKEN_KEY)
            },
            method: params.method == undefined ? 'POST' : params.method,
            dataType: 'json',
			responseType: params.responseType == undefined ? 'text' : params.responseType,
            success: (res) => {
                resolve(res);
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}



function getUserProfile(fn,that){
	uni.getUserProfile({
		success: function(res) {
			uni.setStorageSync(constants.APP_USER_INFO,res.userInfo);
			uni.setStorageSync(constants.IS_SUCCESS_KEY,true);
			loginApp(fn);
		},
		fail: function (err) {
			
		},
		complete:function(){
			that.loginReq = false;
		}
	})
}


/**
 * 登录获取小程序信息
 */
function loginApp(fn){
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			provider = res.provider;
			uni.login({
			  provider: provider,
			  success: function (loginRes) {
				code = loginRes.code;
				//getUserInfo(fn);
				loginMini(fn);
			  }
			});
		}
	}) 
}


/**
 * 登录成功后执行
 * @param {Object} result  登录成功返回的数据
 * @param {Object} fn        登录成功后的回调
 */
function loginSuccess(result, fn) {
    // 保存登陆信息
    uni.setStorageSync(constants.GUO_USER_KEY, result)
    // 保存成功登录标识,token过期判断
    uni.setStorageSync(constants.GUO_IS_LOGIN, true)
      
    if (!result.enabled) {
        uni.showModal({
            showCancel: false,
            title: "提示",
            content: "账号不可用",
            cancelText: "取消",
            confirmText: "确定",
			
        })
		uni.setStorageSync(constants.USER_TOKEN_KEY, '');
        
    } else {
        uni.setStorageSync(constants.USER_TOKEN_KEY, 'bearer' + result.access_token); //把token存入缓存，请求接口数据时要用
		storage.put(constants.TOKEN_DATE,result.access_token,constants.EXP_TIME);
    }
    if (result.userId) {
        uni.setStorageSync(constants.BIND_USER, true);
    } else {
        uni.setStorageSync(constants.BIND_USER, false);
    }
	//设置用户信息
	//setUserInfo();
	
    if (fn) {
        fn()
    }
	
};

/**
 * @param {Object} code 登录小程序
 */
function loginMini(fn){
	
	var params = {
		baseUrl:true,
		miniApp:constants.MINI_TYPE,
	    url: '/login',
	    method: 'POST',
	    dataType: 'json',
	    data: {
			principal:code
		},
	    callBack: res =>  {
	        loginSuccess(res, fn);			
	    }
	};
	request(params);
}

function setUserInfo(userInfo) {
    var params = {
        url: '/u/appConnect/setUserInfo',
        method: 'POST',
        dataType: 'json',
        data: JSON.stringify(uni.getStorageSync(constants.APP_USER_INFO)),
        callBack: function (res) {
        }
    };
   request(params);
}


module.exports = {
    request,
    customRequest,
	loginSuccess,
	loginApp,
	loginMini,
	setUserInfo,
	getUserProfile
};
